package com.erp.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;


import com.erp.dao.ResourcesDAO;
import com.erp.entity.Resources;
import com.erp.form.ErpObject;



//1 加载资源与权限的对应关系
@SuppressWarnings("unused")
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	// 由spring调用
	private ResourcesDAO resourcesMapper;
	public MySecurityMetadataSource(ResourcesDAO resourcesMapper) {
		this.resourcesMapper = resourcesMapper;
		loadResourceDefine();
	}


	public ResourcesDAO getResourcesMapper() {
		return resourcesMapper;
	}

	public void setResourcesMapper(ResourcesDAO resourcesMapper) {
		this.resourcesMapper = resourcesMapper;
	}

	public static Map<String, Collection<ConfigAttribute>> getResourceMap() {
		return resourceMap;
	}

	public static void setResourceMap(
			Map<String, Collection<ConfigAttribute>> resourceMap) {
		MySecurityMetadataSource.resourceMap = resourceMap;
	}


	public static Map<String, Collection<ConfigAttribute>> resourceMap = null;



	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	//加载所有资源与权限的关系
	private void loadResourceDefine() {
 		if (resourceMap == null) {resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
			List<ErpObject> resources = this.resourcesMapper.findAll();
			for (ErpObject resource : resources) {
				Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
				// 以权限名封装为Spring的security Object
				ConfigAttribute configAttribute = new SecurityConfig(((Resources)resource).getName());
				configAttributes.add(configAttribute);
				resourceMap.put(((Resources)resource).getUrl(), configAttributes);
				
			}
		}

		Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();
		
		Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();
	}

	// 返回所请求资源所需要的权限

	public Collection<ConfigAttribute> getAttributes(Object object)throws IllegalArgumentException {
		String url = ((FilterInvocation) object).getRequestUrl();
		if (resourceMap == null) {
			loadResourceDefine();
		}
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();
			if (url.equals(resURL)) {
				Collection<ConfigAttribute> returnCollection = resourceMap.get(resURL);
				return returnCollection;
			}
		}
		return null;
	}

}
